define([
  'jquery',
  'jqueryui',
  'underscore',
  'backbone',
  'backbonecollection',
  'models/schedule/ScheduleModel',
  'collections/schedule/ScheduleCollection',
  'text!templates/schedule/scheduleTemplate.html',
  'msgbox',
  'multiselect'
], function($,JQueryUI, _, Backbone, BackboneCollection, ScheduleModel,ScheduleCollection, scheduleTemplate,MsgBox,Multiselect){

  var ScheduleView = Backbone.View.extend({
    el: $(".mainpanel"),
    events: {'click #saveSchedules' : 'submitButton',
    		'change #dhospitals' : 'renderCalendar'
        } ,
     model:  new ScheduleModel(),
    initialize: function(){
    	//_.bindAll(this, "changed");
        var DoctorHospitals = Backbone.Collection.extend({
            model: Backbone.Model.extend({url:'/getDoctorsHospitals'}),
            url:'/getDoctorsHospitals'
          });	
        this.allHospitals = new DoctorHospitals();

    },
    render: function(){
    	var scheduleCollection = new ScheduleCollection();
    	this.collection = scheduleCollection;
        var lOptions = {};
        var self=this;
        
        lOptions.success = function(){
        	var lOptions1 = {url:'/scheduleAtHospital',data:{hospitalId:self.allHospitals.first().get("id")}};
        	lOptions1.success = function(){
        		self.loadTemplate(scheduleCollection,self.allHospitals);
        	};
        	scheduleCollection.fetch(lOptions1);
   		    
   		    
        };
        this.allHospitals.fetch(lOptions);
        

    },
    renderCalendar: function(){
    	var scheduleCollection = new ScheduleCollection();
    	this.collection = scheduleCollection;
    	var self=this;
        
    	var lOptions1 = {url:'/scheduleAtHospital',data:{hospitalId:parseInt($("#dhospitals").val())}};
    	lOptions1.success = function(){
    		self.loadCalendar(scheduleCollection);
    	};
    	scheduleCollection.fetch(lOptions1);
    	
    },
    loadTemplate: function(scheduleCollection, allHospitals){
    	 var data = {
    			 allHospitals: allHospitals.models
	    	      };
		  var compiledTemplate = _.template( scheduleTemplate, data);		  
	      this.$el.html(compiledTemplate);
  	      $("#dhospitals").multiselect({
  	    	  multiple: false,
  	  		   header: "Select an option",
  	  		   noneSelectedText: "Select an Option",
  	  		   selectedList: 1
  	    	});
			var event =[];
			var i=0;
			var events = scheduleCollection.models;
			var date = new Date(2013,3,21);
			 _.each(events, function(e){ 
				 	var appment = e.get("id");
				 	var addday = e.get("day")-1;
			 		var d = date.getDate()+addday;
			 		event[i] = {title: "",
			 					start: new Date(2013,3,d,e.get("startTime").substring(0,2),e.get("startTime").substring(3,5)), 
			 					end: new Date(2013,3,d,e.get("endTime").substring(0,2),e.get("endTime").substring(3,5)),
			 					allDay: false,
			 					aid: appment};
			 		i=i+1;
				 });

			 $('#calendar').fullCalendar({
	 			theme: true,
	 			aid: 1,
	 			header: false,
	 			editable: true,
	 			events: event,
	 			columnFormat:{
	 				week: 'ddd'
	 			},
	 			defaultView: 'agendaWeek',
	 			dayClick : function(date, allDay, jsEvent, view ){
	 				var event = {title: "",start: date, end: new Date(date.getTime() + 60*60000),allDay: false,aid: 1234};
	 				$('#calendar').fullCalendar( 'renderEvent', event  )
	 	   			}
	 		});
	 		$('#calendar').fullCalendar( 'gotoDate', 2013,3,21);
  	
  },
  loadCalendar: function(scheduleCollection){
		var event =[];
		var i=0;
		var events = scheduleCollection.models;
		var date = new Date(2013,3,21);
		 _.each(events, function(e){ 
			 	var appment = e.get("id");
			 	var addday = e.get("day")-1;
		 		var d = date.getDate()+addday;
		 		event[i] = {title: "",
		 					start: new Date(2013,3,d,e.get("startTime").substring(0,2),e.get("startTime").substring(3,5)), 
		 					end: new Date(2013,3,d,e.get("endTime").substring(0,2),e.get("endTime").substring(3,5)),
		 					allDay: false,
		 					aid: appment};
		 		i=i+1;
			 });

		 $('#calendar').fullCalendar({
 			theme: true,
 			aid: 1,
 			header: false,
 			editable: true,
 			events: event,
 			columnFormat:{
 				week: 'ddd'
 			},
 			defaultView: 'agendaWeek',
 			dayClick : function(date, allDay, jsEvent, view ){
 				var event = {title: "",start: date, end: new Date(date.getTime() + 60*60000),allDay: false,aid: 1234};
 				$('#calendar').fullCalendar( 'renderEvent', event  )
 	   			}
 		});
 		$('#calendar').fullCalendar( 'gotoDate', 2013,3,21);

  },
    close: function(){
    	
    },
    submitButton: function(){
    	var currentEvents = $('#calendar').fullCalendar('clientEvents');
    	var events = this.collection.models;
    	var found=false;
    	var startminute;
    	var starthour;
    	var endminute;
    	var endhour;
    	var aptid=0;
		 for (var i in currentEvents){
			 
			 _.each(events, function(e){ 
				 var id = e.get("id");
				 if(currentEvents[i].aid == id){
					// aptid=id;
					 starthour = currentEvents[i].start.getHours() < 10? "0"+currentEvents[i].start.getHours():currentEvents[i].start.getHours();
					 startminute = currentEvents[i].start.getMinutes()==0?"0"+currentEvents[i].start.getMinutes(): currentEvents[i].start.getMinutes();
					 endhour = currentEvents[i].end.getHours() < 10?"0"+currentEvents[i].end.getHours():currentEvents[i].end.getHours();
					 endminute=currentEvents[i].end.getMinutes()==0?"0"+currentEvents[i].end.getMinutes():currentEvents[i].end.getMinutes();
					 e.set("startTime",starthour+":"+startminute);
					 e.set("endTime",endhour+":"+endminute);
					 e.set("day",currentEvents[i].start.getDay()+1);
					 found = true;
				 }
			 });
			 if(!found){
				 starthour = currentEvents[i].start.getHours() < 10? "0"+currentEvents[i].start.getHours():currentEvents[i].start.getHours();
				 startminute = currentEvents[i].start.getMinutes()==0?"0"+currentEvents[i].start.getMinutes(): currentEvents[i].start.getMinutes();
				 endhour = currentEvents[i].end.getHours() < 10?"0"+currentEvents[i].end.getHours():currentEvents[i].end.getHours();
				 endminute=currentEvents[i].end.getMinutes()==0?"0"+currentEvents[i].end.getMinutes():currentEvents[i].end.getMinutes();
				 this.collection.add({day: currentEvents[i].start.getDay()+1,
					 					startTime: starthour+":"+startminute,
					 					endTime: endhour+":"+endminute,
					 					hospitalId: parseInt($("#dhospitals").val()),
					 					id: aptid
					 				});
				 aptid=aptid-1;
			 }

			 found=false;
		 }
        this.collection.save();
 		 $.msgBox({
			    title:"Appment",
			    content:"Successfully Saved!",
			    type:"info"
			});
    }
  });

  return ScheduleView;
});
